<template>
  <!-- 商品详情顶部内容容器 -->
  <div class="detail-top-content">
    <!-- 左侧图片区域 -->
    <section class="go-flex left-image">
      <!-- 缩略图导航区域 -->
      <div class="thumbnail-nav">
        <!-- 向上滚动按钮 -->
        <button class="nav-arrow up" @click="prevThumbnail" :disabled="currentImageIndex === 0">
          <span class="arrow">
            <UpOutlined />
          </span>
        </button>
        <!-- 缩略图列表 -->
        <div class="thumbnail-list">
          <div v-for="(image, index) in productData.detail_images" :key="index" class="thumbnail"
            :class="{ active: currentImageIndex === index }" @click="selectImage(index)">
            <img :src="image" :alt="`${productData.name} - view ${index + 1}`" />
          </div>
        </div>
        <!-- 向下滚动按钮 -->
        <button class="nav-arrow down" @click="nextThumbnail"
          :disabled="currentImageIndex === productData.detail_images.length - 1">
          <span class="arrow">
            <DownOutlined />
          </span>
        </button>
      </div>

      <!-- 商品主图展示区域 -->
      <div class="product-gallery">
        <!-- 上一张图片按钮 -->
        <button class="gallery-nav prev" @click="prevImage" v-if="currentImageIndex > 0">
          <span class="arrow">&#x2039;</span>
        </button>
        <!-- 主图显示区域 -->
        <div class="main-image">
          <img :src="currentImage" :alt="productData.name" />
        </div>
        <!-- 下一张图片按钮 -->
        <button class="gallery-nav next" @click="nextImage"
          v-if="productData.detail_images && currentImageIndex < productData.detail_images.length - 1">
          <span class="arrow">&#x203A;</span>
        </button>
      </div>
    </section>

    <!-- 商品信息区域 -->
    <section class="product-info">
      <!-- 商品标题和价格 -->
      <div class="product-header">
        <h1 class="brand-name">Duonin</h1>
        <h2 class="product-name">{{ productData.name }}</h2>
        <div class="product-price go-flex-sc">
          <div>{{ useCurrency.currentCurrency.unit }} {{ proxy.$ConvertPrice(productData.min_price) }}</div>
          <div class="product-price-num">
            <img :src="SVG_ICONS.visit" /><span v-show="visitCount">{{ visitCount }}</span>
          </div>
        </div>
      </div>

      <!-- 商品选项区域 -->
      <div class="product-options">
        <!-- 颜色选择 -->
        <div class="option-group">
          <div class="option-label">
            COLOUR:
          </div>
          <div class="color-options">
            <template v-for="item in productData.spec_list" :key="item.name">
              <button v-if="item.name === 'Color'" class="color-option">
                <span v-for="(color, index) in item.value" :key="index" class="color-swatch"
                  :class="{ active: colorActive === color.name }" @click="colorClick(color.name)">
                  <img :src="color.name" alt="">
                </span>
              </button>
            </template>
          </div>
        </div>

        <!-- 尺码选择 -->
        <div class="option-group">
          <div class="option-label size-header">
            <span>SIZE:</span>
            <a class="size-guide" @click="showSizeGuide">SIZE GUIDE</a>
          </div>
          <div class="size-selector">
            <!-- 尺码选择按钮 -->
            <button class="choose-size" @click="toggleSizeDropdown">
              <span>{{ sizeActive || 'CHOOSE SIZE' }}</span>
              <span class="dropdown-arrow" :class="{ 'arrow-up': showSizeDropdown }">▼</span>
            </button>
            <!-- 尺码下拉菜单 -->
            <div class="size-dropdown" v-if="showSizeDropdown">
              <template v-for="item in productData.spec_list" :key="item.name">
                <div class="size-list" v-if="item.name === 'Size'">
                  <button v-for="size in item.value" :key="size.name" class="size-option"
                    :class="{ active: sizeActive === size.name }" @click="selectSize(size.name)">
                    {{ size.name }}
                  </button>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 添加到购物袋和收藏按钮 -->
      <div class="product-actions">
        <div class="action-buttons">
          <!-- 收藏按钮 -->
          <button class="wishlist-button" v-if="!productData.favorite" @click="collectFn(false)">
            <img src="@/assets/svg/favourite-m-default.svg" alt="Add to Wishlist" />
          </button>
          <button class="wishlist-button" v-else @click="collectFn(true)">
            <img src="@/assets/svg/favourite_m_active.svg" alt="Remove from Wishlist" />
          </button>
          <!-- 添加到购物袋按钮 -->
          <button class="add-to-bag" @click="buyFn">
            ADD TO BAG
          </button>
        </div>
      </div>

      <!-- 配送信息 -->
      <!-- TODO 还未对接 -->
      <div class="delivery-info">
        <div class="delivery-icon">
          <img
            src="https://www.reiss.com/static-content/ux-fabric/iconography-graphics/feature/reiss/deliveryreturns-xl-default.svg"
            alt="Delivery" />
        </div>
        <div class="delivery-text">
          <p>FREE NEXT DAY DELIVERY AND RETURNS TO OUR STORES ANDOVER 600 OTHER LOCATIONS. FOR OTHER DELIVERY ANDRETURNS
            OPTIONS AND CHARGES <a href="#" @click="toTerms" class="terms-link">CLICK HERE</a></p>
        </div>
      </div>

      <!-- 商品描述 -->
      <div class="product-description">
        <p :class="{ 'truncated': !showFullDescription }">{{ productData.description }}</p>
        <button v-if="isDescriptionLong" class="read-more" @click="toggleDescription">
          {{ showFullDescription ? 'SHOW LESS' : 'READ MORE' }}
        </button>
      </div>

      <!-- 商品编号 -->
      <div class="product-code">
        <span>PRODUCT CODE:</span>Duonin-{{ productData.id }}
      </div>

      <!-- 商品详情和保养信息 -->
      <div class="product-details" v-for="(item, index) in productData.goods_service" :key="index">
        <button class="details-button" @click="toggleCareInfo(index)">
          <span>{{ item.name }}</span>
          <span class="dropdown-arrow" :class="{ 'arrow-up': showCareInfo[index] }">
            <DownOutlined :style="{ fontSize: '10px' }" />
          </span>
        </button>
        <div class="care-info" v-show="showCareInfo[index]">
          <p>{{ item.content }}</p>
        </div>
      </div>
    </section>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, nextTick, getCurrentInstance } from 'vue';
import { UpOutlined, DownOutlined } from '@ant-design/icons-vue';
import SVG_ICONS from "@/assets/SVG_ICONS";
import { addVisit, addFavorite, deleteFavorite } from "@/api/goods";
import { useCurrencyStore } from '@/store'

interface GoodsService {
  name: string;
  content: string;
}

interface ProductData {
  id: number;
  name: string;
  price: number;
  description: string;
  spec_list: Spec[];
  detail_images: string[];
  code?: string;
  care_instructions?: string;
  favorite?: boolean;
  goods_service?: GoodsService[];
}

const useCurrency = useCurrencyStore()
const { proxy } = getCurrentInstance()

const props = defineProps<{
  detailData: ProductData;
}>();

console.log(props.detailData);

/**
 * 规格值接口定义
 * @interface SpecValue
 * @property {string} name - 规格值名称
 * @property {string} [code] - 规格值代码（可选）
 */
interface SpecValue {
  name: string;
  code?: string;
}

/**
 * 规格接口定义
 * @interface Spec
 * @property {string} name - 规格名称
 * @property {SpecValue[]} value - 规格值数组
 */
interface Spec {
  name: string;
  value: SpecValue[];
}

/**
 * 商品数据接口定义
 * @interface ProductData
 * @property {number} id - 商品ID
 * @property {string} name - 商品名称
 * @property {number} price - 商品价格
 * @property {string} description - 商品描述
 * @property {Spec[]} spec_list - 规格列表
 * @property {string[]} detail_images - 商品详情图片列表
 * @property {string} [code] - 商品编码（可选）
 * @property {string} [care_instructions] - 保养说明（可选）
 */
interface ProductData {
  id: number;
  name: string;
  price: number;
  description: string;
  spec_list: Spec[];
  detail_images: string[];
  code?: string;
  care_instructions?: string;
}


/**
 * 默认商品数据
 * 用于初始化商品数据状态
 */
const defaultProduct: ProductData = {
  id: 0,
  name: '',
  price: 0,
  description: '',
  spec_list: [],
  detail_images: [
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s.jpg?im=Resize,width=750',
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s3.jpg?im=Resize,width=480',
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s4.jpg?im=Resize,width=480',
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s2.jpg?im=Resize,width=480'
  ],
};

// 状态管理
/**
 * 商品数据响应式引用
 */
const productData = ref<ProductData>({ ...defaultProduct });

/**
 * 当前显示的图片索引
 */
const currentImageIndex = ref(0);

/**
 * 当前选中的颜色
 */
const colorActive = ref('');

/**
 * 当前选中的尺码
 */
const sizeActive = ref('');

/**
 * 是否显示保养信息
 */
const showCareInfo = ref<boolean[]>([]);

/**
 * 是否显示完整描述
 */
const showFullDescription = ref(false);

/**
 * 是否显示尺码下拉菜单
 */
const showSizeDropdown = ref(false);

/**
 * 检查描述是否超过3行
 */
const isDescriptionLong = ref(false);

// 计算属性
/**
 * 当前显示的图片URL
 * 根据currentImageIndex计算当前应该显示的图片
 */
const currentImage = computed(() => {
  return productData.value.detail_images[currentImageIndex.value];
});

watch(() => props.detailData, (newVal) => {
  productData.value = { ...newVal };
  let arr = productData.value.spec_list?.filter((item: any) => item.name === 'Color');
  let sizeArr = productData.value.spec_list?.filter((item: any) => item.name === 'Size');
  if (arr && arr.length > 0) {
    colorActive.value = arr[0]?.value[0].name;
  }
  if (sizeArr && sizeArr.length > 0) {
    sizeActive.value = sizeArr[0]?.value[0].name;
  }


},{ immediate: true })

onMounted(() => {
  checkDescriptionLength();
  // 刷新最近浏览
  refreshVisit()
})

const visitCount = ref(null)
// 刷新最近浏览
const refreshVisit = () => {
  addVisit({ id: props.detailData.id }).then((res: any) => {
    if (res.code == 200) {
      visitCount.value = res.result.visit
    }
  })

}


const toTerms = () => {
  // 重新打开一个页签到terms页面
  window.open('/terms', '_blank');
};

// 方法定义
/**
 * 显示上一张图片
 * 如果当前不是第一张图片，则索引减1
 */
const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  }
};

/**
 * 显示下一张图片
 * 如果当前不是最后一张图片，则索引加1
 */
const nextImage = () => {
  if (productData.value.detail_images && currentImageIndex.value < productData.value.detail_images.length - 1) {
    currentImageIndex.value++;
  }
};

/**
 * 选择指定索引的图片
 * @param {number} index - 要选择的图片索引
 */
const selectImage = (index: number) => {
  currentImageIndex.value = index;
};

/**
 * 选择颜色
 * @param {string} color - 要选择的颜色
 */
const colorClick = (color: string) => {
  colorActive.value = color;
};

/**
 * 选择尺码
 * @param {string} size - 要选择的尺码
 */
const sizeClick = (size: string) => {
  sizeActive.value = size;
};

/**
 * 切换保养信息的显示状态
 */
const toggleCareInfo = (index: number) => {
  if (!showCareInfo.value[index]) {
    showCareInfo.value[index] = true;
  } else {
    showCareInfo.value[index] = false;
  }
};

/**
 * 切换商品描述的显示状态
 */
const toggleDescription = () => {
  showFullDescription.value = !showFullDescription.value;
};

/**
 * 显示尺码指南
 * 可以在这里实现尺码指南弹窗
 */
const showSizeGuide = () => {
  // 实现尺码指南弹窗
  console.log('Show size guide');
};

/**
 * 切换尺码下拉菜单的显示状态
 */
const toggleSizeDropdown = () => {
  showSizeDropdown.value = !showSizeDropdown.value;
};

/**
 * 选择尺码并关闭下拉菜单
 * @param {string} size - 要选择的尺码
 */
const selectSize = (size: string) => {
  sizeActive.value = size;
  showSizeDropdown.value = false;
};

/**
 * 添加到购物袋
 * 检查是否已选择尺码和颜色，然后触发buy事件
 */
const buyFn = () => {
  if (!sizeActive.value) {
    alert('Please select a size');
    return;
  }
  if (!colorActive.value) {
    alert('Please select a color');
    return;
  }
  emit('buy', {
    ...productData.value,
    selectedSize: sizeActive.value,
    selectedColor: colorActive.value
  });
};

/**
 * 收藏商品
 * 触发collect事件
 */
const collectFn = async (isFavorite: boolean) => {
  try {
    const res = isFavorite
      ? await deleteFavorite(String(productData.value.id))
      : await addFavorite(String(productData.value.id));

    if (res.code === 200) {
      productData.value.favorite = !isFavorite;
    }
  } catch (error) {
    console.error('Failed to update favorite status:', error);
  }
};

/**
 * 缩略图向上滚动
 * 如果当前不是第一张图片，则索引减1
 */
const prevThumbnail = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  }
};

/**
 * 缩略图向下滚动
 * 如果当前不是最后一张图片，则索引加1
 */
const nextThumbnail = () => {
  if (productData.value.detail_images && currentImageIndex.value < productData.value.detail_images.length - 1) {
    currentImageIndex.value++;
  }
};

/**
 * 检查文本是否超过3行
 */
const checkDescriptionLength = () => {
  nextTick(() => {
    const descriptionElement = document.querySelector('.product-description p');
    if (descriptionElement) {
      const lineHeight = parseInt(getComputedStyle(descriptionElement).lineHeight);
      const height = descriptionElement.clientHeight;
      isDescriptionLong.value = height > lineHeight * 3;
    }
  });
};

// 监听描述内容变化
watch(() => productData.value.description, () => {
  nextTick(() => {
    checkDescriptionLength();
  });
});

// Emits 定义
/**
 * 组件事件定义
 * @property {Function} buy - 购买事件，传递商品数据和选择的尺码、颜色
 * @property {Function} collect - 收藏事件，传递商品数据
 */
const emit = defineEmits<{
  (e: 'buy', product: ProductData & { selectedSize: string; selectedColor: string }): void;
}>();
</script>

<style lang="scss" scoped>
/* 商品详情顶部内容容器样式 */
.detail-top-content {
  display: grid;
  grid-template-columns: 1fr;
  margin: 0 auto;
  font-family: Arial, sans-serif;

  /* 响应式布局：在中等屏幕及以上使用两列布局 */
  @media (min-width: 768px) {
    grid-template-columns: 1fr 1fr;
  }
}

/* 左侧图片区域样式 */
.left-image {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: top;
  gap: 25px;
}

/* 商品图片展示区域样式 */
.product-gallery {
  position: relative;
  width: 100%;
  max-width: 470px;
  margin: 0;

  /* 主图样式 */
  .main-image {
    width: 100%;
    max-width: 470px;
    max-height: 627px;
    height: auto;
    aspect-ratio: 3 / 4;
    overflow: hidden;
    margin-bottom: 10px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  /* 图片导航按钮样式 */
  .gallery-nav {
    position: absolute;
    top: 46%;
    transform: translateY(-50%);
    background: none;
    border: none;
    font-size: 24px;
    color: #000;
    cursor: pointer;
    padding: 10px;
    z-index: 2;

    &.prev {
      left: 10px;
    }

    &.next {
      right: 10px;
    }
  }
}

/* 缩略图导航样式 */
.thumbnail-nav {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 0;
  width: 90px;
  height: 627px;
  position: relative;

  /* 导航箭头按钮样式 */
  .nav-arrow {
    width: 100%;
    height: 30px;
    background: none;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    color: #000;
    font-size: 12px;

    &:disabled {
      opacity: 0.3;
      cursor: not-allowed;
    }

    &.up {
      margin-bottom: 5px;
    }

    &.down {
      margin-top: 5px;
    }
  }

  /* 缩略图列表样式 */
  .thumbnail-list {
    flex: 1;
    display: flex;
    overflow-y: auto;
    flex-direction: column;
    scrollbar-width: none;
    align-items: center;
    justify-content: space-between;

    /* 隐藏滚动条 */
    &::-webkit-scrollbar {
      display: none;
    }
  }

  /* 单个缩略图样式 */
  .thumbnail {
    width: 90px;
    height: 120px;
    cursor: pointer;
    opacity: 0.6;
    transition: opacity 0.3s;
    margin-bottom: 8px;

    /* 激活状态样式 */
    &.active {
      opacity: 1;
      border-bottom: 2px solid #000;
    }

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  /* 响应式布局：在小屏幕上隐藏缩略图导航 */
  @media (max-width: 1020px) {
    display: none;
  }
}

/* 商品信息区域样式 */
.product-info {
  width: 100%;
  padding: 0;
  max-width: 470px;
  margin: 0 auto;

  /* 商品标题和价格样式 */
  .product-header {
    margin-bottom: 16px;

    .brand-name {
      font-size: 14px;
      font-weight: bold;
      margin: 0;
      letter-spacing: 0.5px;
    }

    .product-name {
      font-size: 14px;
      font-weight: bold;
      margin: 0 0 5px;
      letter-spacing: 0.5px;
    }

    .product-price {
      font-size: 14px;
      font-weight: bold;
    }

    .product-price-num {
      font-size: 12px;

      img {
        width: 25px;
        height: 25px;
      }

      span {
        position: relative;
        bottom: -2px;
      }
    }
  }

  /* 商品选项样式 */
  .product-options {
    border-top: 1px solid #e5e5e5;

    /* 选项组样式 */
    .option-group {
      .option-label {
        font-size: 12px;
        padding-top: 16px;
        font-weight: bold;
        margin-bottom: 2px;
      }

      /* 尺码标题样式 */
      .size-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 10px;
        font-weight: bold;

        .size-guide {
          font-size: 12px;
          text-decoration: underline;
          cursor: pointer;
          font-weight: bold;
          color: #000;
          margin-top: 0;
          padding: 0;
          background-color: none;
          border-radius: 0;
          border-left: 0;
        }

        span {
          font-weight: bold;
        }
      }
    }

    /* 颜色选项样式 */
    .color-options {
      .color-option {
        // width: 30px;
        // height: 30px;
        border: none;
        background: none;
        padding: 2px;
        cursor: pointer;
        display: flex;

        .color-swatch {
          display: block;
          border-radius: 50%;
          // border: 1px solid #000;
          padding: 2px;

          /* 激活状态样式 */


          img {
            width: 30px;
            height: 30px;
            border-radius: 50%;
          }
        }

        .color-swatch.active {
          border: 1px solid #000;
        }
      }
    }

    /* 尺码选择器样式 */
    .size-selector {
      position: relative;
      width: 100%;
      margin-bottom: 37px;

      /* 尺码选择按钮样式 */
      .choose-size {
        width: 100%;
        padding: 7.5px 15px;
        background: white;
        border: 1px solid rgba(0, 0, 0, 0.87);
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        cursor: pointer;
        text-align: left;

        .dropdown-arrow {
          font-size: 10px;
          transition: transform 0.3s;

          /* 箭头向上旋转 */
          &.arrow-up {
            transform: rotate(180deg);
          }
        }
      }

      /* 尺码下拉菜单样式 */
      .size-dropdown {
        position: absolute;
        top: 100%;
        left: 0;
        width: 100%;
        background: white;
        border-top: none;
        z-index: 10;
      }

      /* 尺码列表样式 */
      .size-list {
        max-height: 250px;
        overflow-y: auto;
        box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1);
        padding: 8px 0;

        .size-option {
          width: 100%;
          padding: 8px 15px;
          background: none;
          border: none;
          text-align: left;
          font-size: 12px;
          cursor: pointer;

          &:hover {
            background: #000;
            color: #fff;
            border: 1px solid #fff;
          }

          /* 激活状态样式 */
          &.active {
            font-weight: bold;
          }
        }
      }
    }
  }

  /* 商品操作按钮样式 */
  .product-actions {
    margin-bottom: 30px;

    .action-buttons {
      display: flex;
      gap: 10px;
      width: 100%;

      /* 收藏按钮样式 */
      .wishlist-button {
        width: 38px;
        height: 38px;
        border: 1px solid #e0e0e0;
        background: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }

      /* 添加到购物袋按钮样式 */
      .add-to-bag {
        flex: 1;
        background: #000;
        color: white;
        border: none;
        height: 36px;
        line-height: 36px;
        width: 100%;
        max-width: 100%;
        font-size: 14px;
        font-weight: bold;
        letter-spacing: 0.5px;
        cursor: pointer;

        &:hover {
          background: #333;
        }
      }
    }
  }

  /* 配送信息样式 */
  .delivery-info {
    border-top: 1px solid #e0e0e0;
    padding: 20px 0;
    font-size: 12px;
    line-height: 1.6;
    display: flex;

    .delivery-icon {
      margin-right: 15px;
      display: flex;
      align-items: center;
    }

    p {
      margin: 0px;
    }

    .terms-link {
      color: #000;
      text-decoration: underline;
    }
  }

  /* 商品描述样式 */
  .product-description {
    margin-bottom: 20px;
    font-size: 12px;
    line-height: 1.6;

    p {
      margin: 0;
      transition: max-height 0.3s ease;

      &.truncated {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .read-more {
      background: none;
      border: none;
      color: #000;
      text-decoration: underline;
      padding: 0;
      font-size: 12px;
      cursor: pointer;
      width: 100%;
      font-weight: bold;
      text-align: right;
      margin-top: 8px;
    }
  }

  /* 商品编号样式 */
  .product-code {
    font-size: 12px;
    color: #333;
    padding-bottom: 5px;
    border-bottom: 1px solid #e0e0e0;

    span {
      color: #000;
      font-weight: bold;
      margin-right: 6px;
    }
  }

  /* 商品详情和保养信息样式 */
  .product-details {
    border-bottom: 1px solid #e0e0e0;

    .details-button {
      width: 100%;
      padding: 12px 0 4px 0;
      background: none;
      border: 0;
      font-size: 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;

      span {
        border: none;
        color: #000;
        font-weight: bold;
      }

      .dropdown-arrow {
        font-size: 10px;
        transition: transform 0.3s;

        /* 箭头向上旋转 */
        &.arrow-up {
          transform: rotate(180deg);
        }
      }
    }
  }
}

/* 响应式布局：小屏幕样式 */
@media (max-width: 767px) {
  .product-detail-container {
    gap: 20px;
    padding: 10px;
  }

  .product-info {
    padding: 0;
  }
}
</style>
